package com.runen.infinitemovement.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.fragment.ConsultFragmentV2;
import com.runen.infinitemovement.fragment.HomeFragment;
import com.runen.infinitemovement.fragment.LongRoadFragment;
import com.runen.infinitemovement.fragment.MeFragment;
import com.runen.infinitemovement.fragment.SportsFragment;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.AdInfoEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.GetTopIdEntity;
import com.runen.infinitemovement.model.entity.JudgeBranchCheckEntity;
import com.runen.infinitemovement.model.entity.StepForEntity;
import com.runen.infinitemovement.model.entity.UpdataInfo;
import com.runen.infinitemovement.model.enums.SPCompat;
import com.runen.infinitemovement.steputil.StepUtil;
import com.runen.infinitemovement.tool.AppDownloadManager;
import com.runen.infinitemovement.tool.NotificationsUtils;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.AppUtils;
import com.runen.rxnetlibrary.utils.LogUtil;
import com.runen.rxnetlibrary.utils.SharePreferenceUtils;
import com.runen.rxnetlibrary.utils.TimeUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity {
    private static MainActivity mainActivity;

    @BindView(R.id.fl_main)
    FrameLayout flMain;
    @BindView(R.id.tv_home)
    RadioButton tvHome;
    @BindView(R.id.tv_long_road)
    RadioButton tvLongRoad;
    @BindView(R.id.tv_sports)
    RadioButton tvSports;
    @BindView(R.id.tv_consult)
    RadioButton tvConsult;
    @BindView(R.id.tv_me)
    RadioButton tvMe;
    @BindView(R.id.rg_main)
    RadioGroup rgMain;
    private FragmentTransaction transaction;
    private HomeFragment homeFragment;
    private LongRoadFragment longRoadFragment;
    private SportsFragment sportsFragment;
    private MeFragment meFragment;
    //    private ConsultFragment consultFragment;
    private ConsultFragmentV2 consultFragment;
    private PackageManager pm;
    private PackageInfo pi = null;
    private int versionCode;
    FragmentManager supportFragmentManager;

    private String curSelDate;

    private DecimalFormat df = new DecimalFormat("#.##");
    private boolean isBind = false;
    /**
     * 定时任务
     */
    private TimerTask timerTask;
    private Timer timer;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @SuppressLint("WrongConstant")
    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        mainActivity = this;
        ButterKnife.bind(this);
        curSelDate = TimeUtil.getCurrentDate();
        supportFragmentManager = getSupportFragmentManager();
        initData();

        judgeBranch();
        /**
         * 版本更新
         */
        onVersions();
        rgMain.check(R.id.tv_home);
        /**
         * 广告信息
         */
        initAdInfo();
        requestPermission();
        initStep();
    }

    private void initStep() {
        if (!StepUtil.isSupportStep(this)) {
            ToastUtils.showShort("手机暂不支持计步功能");
            return;
        }
        steps = StepUtil.getTodayStep(MainActivity.this);
        onUpDataStep();
    }

    /**
     * 获取广告信息
     */
    private void initAdInfo() {
        new UserAPI().adInfo(new BaseResultCallback<AdInfoEntity>() {
            @Override
            public void onResponse(AdInfoEntity response) {
                if (response.code == 0) {
                    if (response.data != null && response.data.size() > 0) {
                        UserAPI.saveAdInfo(response);
                    } else {
                        UserAPI.clearAD();
                    }
                }
            }
        });
    }

    /**
     * 计步开始
     */
    @SuppressLint("WrongConstant")
    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, 1);
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACTIVITY_RECOGNITION)) {
//                    DialogHelper.showRationaleDialog(shouldRequest);
                }
            } else {
            }
        } else {
        }


        NotificationsUtils.openNotification(this);
    }


    /**
     * 版本更新
     */
    public void onVersions() {
        new UserAPI().getUpdata(new BaseResultCallback<UpdataInfo>() {
            @Override
            public void onResponse(UpdataInfo response) {
                if (response != null) {
                    pm = getPackageManager();
                    try {
                        pi = pm.getPackageInfo(getPackageName(), 0);
                        versionCode = pi.versionCode;
                        int versionCode2 = Integer.parseInt(response.versionCode);
                        if (versionCode < versionCode2) {
                            new AppDownloadManager(MainActivity.this, response.downloadUrl, response.log);
                        }
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                if (!TextUtils.isEmpty(body)) {
                    if (body.contains("Invalid access token")) {
                        UserAPI.clearLogin();
                        startActivity(new Intent(MainActivity.this, LoginActivity2.class));
                        finish();
                    }
                }
                super.onError(e, body);
            }
        });
    }

    /**
     * 判断是否通过了部门审核
     */
    private void judgeBranch() {
        new UserAPI().judgeCheck(new BaseResultCallback<JudgeBranchCheckEntity>() {
            @Override
            public void onResponse(JudgeBranchCheckEntity response) {
                if (response.code == 0) {
                    if (response.data == 1) {
                        Intent intent = new Intent(MainActivity.this, InputTeamCodeActivity.class);
                        intent.putExtra("BranchCheck", 1);
                        startActivity(intent);
                        finish();
                    } else if (response.data == 3) {
                        ToastUtils.showShort("请重新选择部门");
                        startActivity(new Intent(MainActivity.this, InputTeamCodeActivity.class));
                        finish();
                    } else if (response.data == 0) {
//                        startActivity(new Intent(MainActivity.this, CheckJoinUsRecommendActivity.class));
                        startActivity(new Intent(MainActivity.this, InputTeamCodeActivity.class));
                        finish();
                    } else if (response.data == 4) {//邀请
                        topId();
                    }
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                if (!TextUtils.isEmpty(body)) {
                    if (body.contains("Invalid access token")) {
                        UserAPI.clearLogin();
                        startActivity(new Intent(MainActivity.this, LoginActivity2.class));
                        finish();
                    }
                }
                super.onError(e, body);
            }
        });
    }

    private void topId() {
        showDialog();
        new UserAPI().getTopId(new BaseResultCallback<GetTopIdEntity>() {
            @Override
            public void onResponse(GetTopIdEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (!TextUtils.isEmpty(response.data)) {
                        Intent intent = new Intent(MainActivity.this, CheckTeamActivity.class);
                        intent.putExtra("companyId", response.data);
                        startActivity(intent);
                        finish();
                    }
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                dismissDialog();
            }
        });
    }


    public void initData() {
        rgMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                transaction = supportFragmentManager.beginTransaction();
                hideFragment();
                switch (checkedId) {
                    case R.id.tv_home:
                        if (homeFragment == null) {
                            homeFragment = new HomeFragment();
                            transaction.add(R.id.fl_main, homeFragment);
                        }
                        transaction.show(homeFragment);
                        break;
                    case R.id.tv_long_road:
                        if (longRoadFragment == null) {
                            longRoadFragment = new LongRoadFragment();
                            transaction.add(R.id.fl_main, longRoadFragment);
                        }
                        transaction.show(longRoadFragment);
                        boolean firstMyRoad = SharePreferenceUtils.getBoolean(MainActivity.this, SPCompat.FIRST_START_MY_LONG_ROAD, true);
                        if (firstMyRoad) {
                            Intent intent = new Intent(MainActivity.this, IntroduceMyLoadActivity.class);
                            startActivity(intent);
                        }
                        break;
                    case R.id.tv_sports:
                        if (sportsFragment == null) {
                            sportsFragment = new SportsFragment();
                            transaction.add(R.id.fl_main, sportsFragment);
                        }
                        transaction.show(sportsFragment);
                        break;
                    case R.id.tv_consult:
                        if (consultFragment == null) {
//                            consultFragment = new ConsultFragment();
                            consultFragment = new ConsultFragmentV2();
                            transaction.add(R.id.fl_main, consultFragment);
                        }
                        transaction.show(consultFragment);
                        break;
                    case R.id.tv_me:
                        if (meFragment == null) {
                            meFragment = new MeFragment();
                            transaction.add(R.id.fl_main, meFragment);
                        }
                        transaction.show(meFragment);
                        break;
                }
                transaction.commitAllowingStateLoss();
            }
        });

    }

    public void jumpToTuiJian() {
        rgMain.check(R.id.tv_home);
    }

    public void jumpToYundong() {
        rgMain.check(R.id.tv_sports);
    }

    public void jumpToLongRoad() {
        rgMain.check(R.id.tv_long_road);
    }

    private void hideFragment() {
        if (homeFragment != null) {
            //隐藏
            transaction.hide(homeFragment);
        }
        if (longRoadFragment != null) {
            transaction.hide(longRoadFragment);
        }
        if (sportsFragment != null) {
            //隐藏
            transaction.hide(sportsFragment);
        }
        if (consultFragment != null) {
            transaction.hide(consultFragment);
        }
        if (meFragment != null) {
            //隐藏
            transaction.hide(meFragment);
        }
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            AppUtils.exitShowToast();
            return false;
        }
        return super.dispatchKeyEvent(event);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventBusEntity event) {
        switch (event.getMsg()) {
            case 7:
                finish();
                break;
            case 99:
                judgeBranch();
                break;
            case 101:
                onUpDataStep();
                break;
            case EventBusEntity.CODE_104:
                jumpToTuiJian();
                break;
            case EventBusEntity.CODE_109:
                jumpToLongRoad();
                break;
        }
    }

    public static void checkFragment(int flag) {
        switch (flag) {
            case 88:
                mainActivity.rgMain.check(R.id.tv_sports);
                break;
            case 77:
                mainActivity.rgMain.check(R.id.tv_consult);
                break;
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Runtime.getRuntime().gc();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        int message = intent.getIntExtra("STEP", 0);
        LogUtil.e("message_step", message + "");
        if (message == 1) {
            mainActivity.rgMain.check(R.id.tv_sports);
        }
        super.onNewIntent(intent);

    }

    private void goFor() {
        new UserAPI().stepFor(new BaseResultCallback<StepForEntity>() {
            @Override
            public void onResponse(StepForEntity response) {
                EventBus.getDefault().post(new EventBusEntity(EventBusEntity.CODE_110, response.data.totalCompletionRatePlus));
            }
        });
    }

    private int steps;

    private void onUpDataStep() {
        JSONObject object = new JSONObject();
        try {
            object.put("step", steps);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new UserAPI().upDataStep(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() != 0) {
                    ToastUtils.showShort(response.getMessage());
                    goFor();
                }
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (longRoadFragment != null && longRoadFragment.answerPopupWindow != null
                && longRoadFragment.answerPopupWindow.isShowing()) {
            return false;
            //源码建议返回true表示自身消费这个事件，不传递给子view，这里测试过返回true-false都可以
        }
        if (longRoadFragment != null && longRoadFragment.pathSectionCompletePopupWindow != null
                && longRoadFragment.pathSectionCompletePopupWindow.isShowing()) {
            return false;
            //源码建议返回true表示自身消费这个事件，不传递给子view，这里测试过返回true-false都可以
        }
        return super.dispatchTouchEvent(event);
    }
}
